using System;
using System.Collections.Generic;
using Microsoft.Data.Sqlite;
using 第六次作业.entity;

namespace 第六次作业.utils.crud;

public class LogRepository
{
    public void Create(string action)
    {
        using (SqliteConnection connection = DatabaseUtil.GetConnection())
        {
            connection.Open();
            SqliteCommand command = connection.CreateCommand();
            command.CommandText = "INSERT INTO Log (Timestamp, Action) VALUES (@Timestamp, @Action)";
            command.Parameters.AddWithValue("@Timestamp", DateTime.Now);
            command.Parameters.AddWithValue("@Action", action);
            command.ExecuteNonQuery();
        }
    }

    public List<Log> GetAll()
    {
        var logs = new List<Log>();
        using (SqliteConnection connection = DatabaseUtil.GetConnection())
        {
            connection.Open();
            SqliteCommand command = connection.CreateCommand();
            command.CommandText = "SELECT * FROM Log";
            SqliteDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                Log log = new Log
                {
                    Id = reader.GetInt32(0),
                    Timestamp = reader.GetDateTime(1),
                    Action = reader.GetString(2)
                };
                logs.Add(log);
            }
        }
        return logs;
    }
}